#! -*- coding:utf-8 -*-
import logging
import os
import time
from datetime import datetime, timedelta

from django.conf import settings
from django.core.management.base import BaseCommand
from pymongo import MongoClient

from common.order.model import PayOrder
from common.utils.export import redirect_to_file
from common.utils.mg import parse_query
from common.utils.tz import local_str_to_utc_str, utc_str_to_local_str

_LOGGER = logging.getLogger(__name__)

mg = MongoClient(settings.MONGO_ADDR).paychannel_stat


def gen_file_name(channel_id, start):
    return 'MG_' + start.strftime('%Y%m%d') + '_' + str(channel_id) + '.xlsx'


def check_file_exist(channel_id, start):
    return os.path.exists('/tmp/export_data/' + gen_file_name(channel_id, start))


def gen_channel_success_day_orders_xlsx(channel_id, start, end):
    t1 = int(time.time())
    orders = PayOrder.query.filter(PayOrder.channel_id == channel_id).filter(PayOrder.status == 2). \
        filter(PayOrder.payed_at >= local_str_to_utc_str(unicode(start))). \
        filter(PayOrder.payed_at < local_str_to_utc_str(unicode(end))).all()
    list = []
    for order in orders:
        data_row = ['D_' + str(order.id), 'T_' + str(order.out_trade_no), order.third_id or '-',
                    utc_str_to_local_str(unicode(order.created_at)), order.mch_id,
                    order.total_fee, utc_str_to_local_str(unicode(order.payed_at)) or '-']
        if order.created_at.day != order.payed_at.day:
            data_row.append('yes')
        else:
            data_row.append('no')

        if order.extend and 'reason' in order.extend:
            data_row.append('yes')
        else:
            data_row.append('no')
        list.append(data_row)
    cn_header = ['id', u'商户订单号', u'通道订单号', u'创建时间', u'商户ID', u'金额', u'到账时间', u'是否隔天', u'是否补单']
    rsp = redirect_to_file(list, cn_header, gen_file_name(channel_id, start))
    t2 = int(time.time())
    print 'spend  %s second, generate file: %s' % (t2 - t1, rsp['url'])


# 0 1 * * * cd /home/ubuntu/af-env/payservice;/home/ubuntu/af-env/bin/python manage.py gen_mg_day_report 1
# 每天凌晨一点执行一次
class Command(BaseCommand):
    # 参数描述 days：统计N天前
    def handle(self, n_days_before, **options):
        print 'start'
        _LOGGER.info('gen_mg_day_report start')
        n = int(n_days_before)
        now = datetime.utcnow() + timedelta(hours=8)
        start = datetime.strptime("{}-{}-{} 0:0:0".format(now.year, now.month, now.day), "%Y-%m-%d %H:%M:%S")
        start = start + timedelta(days=-n)
        end = (start + timedelta(days=1))

        query_dct = {}
        query_dct['start'] = '''{"$gte":"''' + start.strftime('%Y-%m-%d %H:%M:%S') + '''","$lt":"''' \
                             + end.strftime('%Y-%m-%d %H:%M:%S') + '''"}'''

        query_cond = parse_query(query_dct)
        items = mg.channel_status.find(query_cond)  # channel_status start/end time is local
        print query_cond
        for item in items:
            print item['channel_id']
            if check_file_exist(item['channel_id'], start):
                print 'check_file_exist true'
                continue
            gen_channel_success_day_orders_xlsx(item['channel_id'], start, end)

        # 删除两周前生成的文件
        cmd = 'rm MG_' + '_' + (start + timedelta(days=-30)).strftime('%Y%m%d') + '*'
        print cmd
        os.system(cmd)
        _LOGGER.info('gen_mg_day_report end')
